package com.seveneight.baijiesteward.ui.user.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.InputType;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.seveneight.baijiesteward.R;
import com.seveneight.baijiesteward.adapter.CardListAdapter;
import com.seveneight.baijiesteward.base.BaseActivity;
import com.seveneight.baijiesteward.base.MessageBean;
import com.seveneight.baijiesteward.bean.CardBean;
import com.seveneight.baijiesteward.http.AppConfig;
import com.seveneight.baijiesteward.ui.main.activity.WebActivity;
import com.seveneight.baijiesteward.ui.user.contract.CardListContract;
import com.seveneight.baijiesteward.ui.user.contract.RemoveCardContract;
import com.seveneight.baijiesteward.ui.user.contract.SetDefaultContract;
import com.seveneight.baijiesteward.ui.user.contract.UpgradeContract;
import com.seveneight.baijiesteward.ui.user.presenter.CardListPresenter;
import com.seveneight.baijiesteward.ui.user.presenter.RemoveCardPresenter;
import com.seveneight.baijiesteward.ui.user.presenter.SetDefaultPresenter;
import com.seveneight.baijiesteward.ui.user.presenter.UpgradePresenter;
import com.seveneight.baijiesteward.utils.RecyclerviewInitUtil;
import com.seveneight.baijiesteward.utils.ToastUtil;
import com.seveneight.baijiesteward.utils.WindowUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by user1 on 2018/3/27.
 */

public class ManagerCardActivity extends BaseActivity implements View.OnClickListener, CardListContract.CardListView, RemoveCardContract.RemoveCarView, SetDefaultContract.SetDefaultView, UpgradeContract.UpgradeView {

    UpgradeContract.UpgradePresenter upgradePresenter;
    SetDefaultContract.SetDefaultPresenter setDefaultPresenter;
    RemoveCardContract.RemoveCardPresenter removeCardPresenter;
    CardListContract.CardListPresenter cardListPresenter;
    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.recyclerview)
    LRecyclerView recyclerview;
    private TextView tv_addcard;
    private CardListAdapter adapter;
    private LRecyclerViewAdapter lRecyclerViewAdapter;
    private List<CardBean> data = new ArrayList<>();
    private CardBean cardBean;
    private int position;
    private int type;
    private String upGradeRankID;
    private String bankCardId;

    @Override
    protected void initLayout() {
        setContentView(R.layout.fragment_managercard);
    }

    @Override
    protected void initView() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            type = bundle.getInt("type");
            if (type == 0) {
                tv_title.setText("结算卡管理");
            } else if (type == 1) {
                tv_title.setText("选择结算卡");
                upGradeRankID = bundle.getString("UpGradeRankID");
            } else if (type == 2) {
                tv_title.setText("选择收款卡");
            }
        }
        View footer = LayoutInflater.from(activity).inflate(R.layout.layout_cardlistbottom, (ViewGroup) findViewById(android.R.id.content), false);
        tv_addcard = (TextView) footer.findViewById(R.id.tv_addcard);
        RecyclerviewInitUtil.initLineRecycler(activity, recyclerview);
        recyclerview.setPullRefreshEnabled(false);
        adapter = new CardListAdapter(activity);
        lRecyclerViewAdapter = new LRecyclerViewAdapter(adapter);
        lRecyclerViewAdapter.addFooterView(footer);
        recyclerview.setAdapter(lRecyclerViewAdapter);
    }

    @Override
    protected void initData() {
        setDefaultPresenter = new SetDefaultPresenter(this);
        removeCardPresenter = new RemoveCardPresenter(this);
        cardListPresenter = new CardListPresenter(this);
        upgradePresenter = new UpgradePresenter(this);
        getData();
    }

    private void getData() {
        adapter.clear();
        cardListPresenter.getCardList(activity, jsonFormat.commonParam());
    }

    @Override
    protected void setListener() {
        iv_back.setOnClickListener(this);
        tv_addcard.setOnClickListener(this);
        recyclerview.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                getData();
            }
        });

        recyclerview.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {

            }
        });
        lRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (type == 0) {
                    return;
                }
                if (type == 1) {
                    CardBean cardBean = adapter.getDataList().get(position);
                    bankCardId = cardBean.getDebitCardID();
                    showInputDialogCustomInvalidation();
                }
                if (type == 2) {
                    CardBean cardBean = adapter.getDataList().get(position);
                    Intent intent = new Intent();
                    intent.putExtra("bean", cardBean);
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_addcard:
                Bundle bundle = new Bundle();
                bundle.putInt("size", data.size());
                Intent i = new Intent(activity, AddCarActivity.class);
                i.putExtras(bundle);
                startActivityForResult(i, AppConfig.REQUEST_CODE_1);
                break;
        }
    }

    @Override
    public void reBackCardList(List<CardBean> data) {
        this.data = data;
        recyclerview.refreshComplete(data.size());
        adapter.addAll(data);
        lRecyclerViewAdapter.notifyDataSetChanged();
    }

    @Override
    public void reBackRemoveStatus() {
        adapter.remove(position);
    }

    @Override
    public void reBackSetDefaultStatus() {
        getData();
    }

    @Subscribe
    public void onEvent(MessageBean bean) {
        switch (bean.getType()) {
            case 1:
                position = bean.getPos();
                cardBean = (CardBean) bean.getData();
                ActionSheetDialogNoTitle();
                break;
        }
    }

    private void ActionSheetDialogNoTitle() {
        final String[] stringItems = {"编辑", "删除", "设为默认"};
        final ActionSheetDialog dialog = new ActionSheetDialog(activity, stringItems, null);
        dialog.isTitleShow(false).show();
        dialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("data", cardBean);
                        Intent i = new Intent(activity, EditCardActivity.class);
                        i.putExtras(bundle);
                        startActivityForResult(i, AppConfig.REQUEST_CODE_1);
                        break;
                    case 1:
                        if (cardBean.getIsDefault()) {
                            showDialog("不能删除默认卡");
                            return;
                        }
                        removeCardPresenter.removeCard(activity, jsonFormat.setDebitCard(cardBean.getDebitCardID()));
                        break;
                    case 2:
                        setDefaultPresenter.setDefault(activity, jsonFormat.setDebitCard(cardBean.getDebitCardID()));
                        break;

                }
                dialog.dismiss();
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!EventBus.getDefault().isRegistered(this)) {
//            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void upgradeStatus(String PayInfo) {
        Intent intent = new Intent(activity, WebActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("url", PayInfo);
        intent.putExtras(bundle);
        startActivityForResult(intent, AppConfig.REQUEST_CODE_0);
    }

    public void showInputDialogCustomInvalidation() {
        new MaterialDialog.Builder(ManagerCardActivity.this)
                .title("温馨提示")
                .backgroundColorRes(R.color.white)
                .titleColorRes(R.color.mainblue)
                .positiveColorRes(R.color.mainblue)
                .contentColorRes(R.color.graytext)
                .widgetColorRes(R.color.mainblue)
                .content("请输入交易密码")
                .inputType(
                        InputType.TYPE_TEXT_VARIATION_PASSWORD)
                .positiveText("确定")
                .input(
                        "",
                        "", false,
                        (dialog, input) -> stratToPay(input.toString()))
                .show();
    }

    private void stratToPay(String pwd) {
        upgradePresenter.upUserGrade(activity, jsonFormat.upGrade(upGradeRankID, "0", bankCardId, pwd));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppConfig.REQUEST_CODE_0 && resultCode == RESULT_OK) {
            setResult(RESULT_OK);
            finish();
        } else if (requestCode == AppConfig.REQUEST_CODE_1 && resultCode == RESULT_OK) {
            getData();
        }
    }
}
